<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/01/0001
 * Time: 11:37
 */

namespace app\sports_admin\controller;

use app\exception\ContentsException;
use app\sports_admin\model\SportsProject;
use think\Request;
use app\sports_admin\model\Contents as ContentsModel;
use app\sports_admin\service\Contents as ContentsService;
use app\sports_admin\model\Region as RegionModel;
class Contents extends Base
{
    protected $beforeActionList = [
        'isResource'=>['only'=>'index,add,insert,edit,update,delete'],
        'operationSelect'=>['only'=>'index,contentslist,add,edit'],
        'operationDelete'=>['only'=>'delete'],
        'operationInsert'=>['only'=>'insert'],
        'operationUpdate'=>['only'=>'update']
    ];
    //内容管理首页
    public function index()
    {
        $project = SportsProject::select();
        return view('index',compact('project'));
    }
    /**
     * 内容管理列表
     * @param $page 第几页
     * @param $rows 每页显示的条数
     * @param $sort 要排序的字段
     * @param $sortOrder 升序/降序
     * @param $searchName 要搜索的字段
     */
    public function contentsList()
    {
        $params = Request::instance()->only(['page','rows','sort','sortOrder','searchName']);
        return ContentsModel::contentsList(
            $params['page'],$params['rows'],$params['sort'],$params['sortOrder'],$params['searchName']
        );
    }
    //添加页面
    public function add()
    {
        //获取项目
        $project = SportsProject::select();
        return view('add',compact('project'));
    }
    /**
     * 添加内容
     */
    public function insert(Request $request)
    {
        if($request->isAjax()){
            return ContentsService::insert();
        }
    }
    /**
     * 编辑内容页面
     * @param $id
     */
    public function edit(Request $request)
    {
        $id = intval($request->get('id'));
        //获取项目
        $project = SportsProject::select();
        $regionId = intval($request->get('region_id'));
        //获取城市名称
        $city = RegionModel::getCityName($regionId);
        //获取内容信息
        $contentsInfo = ContentsModel::contentsFind($id);
        return view('edit',compact('city','contentsInfo','project'));
    }
    /**
     * 更新信息
    */
    public function update(Request $request)
    {
        if($request->isAjax()){
            return ContentsService::update();
        }
    }
    /**
     *删除
     * @param $id 内容信息id
    */
    public function delete(Request $request)
    {
        if($request->isAjax()){
            $id = intval($request->post('id'));
            $bool = ContentsModel::destroy($id);
            if(!$bool){
                throw new ContentsException([
                    'msg'=>'内容信息删除失败',
                    'errorCode'=>400
                ]);
            }
            return json(['msg'=>'删除成功','code'=>200]);
        }
    }
}